import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {ModalController} from "ionic-angular";
import {HttpProvider} from "@providers/http";
import {StorageProvider} from "@providers/storage";
import {DialogProvider} from "@providers/dialog";
import {PagingConfig, PagingProvider} from "@providers/paging";
import {Util} from "@providers/util";
import {env} from "@env/environment";

@Injectable()
export class InterfaceProvider {

  constructor(private http: HttpProvider,
              private modalCtrl: ModalController,
              private storageService: StorageProvider,
              private dialogService: DialogProvider,
              private pagingService: PagingProvider) {
  }

  getJLWBDH(key) {
    return Observable.create((observer) => {
      let userInfo = this.storageService.read("userInfo");
      this.http.get("/JLInterface/getJLWBDH.do", {
        XmlData: JSON.stringify({"key": key}),
        SessionID: userInfo["SessionID"]
      }).subscribe(message => {
        observer.next(message);
      }, error => {
        this.dialogService.showToast(error);
      });
    });
  }

  get(config: any, pagingConfig?: PagingConfig): Observable<any> {
    let userInfo = this.storageService.read("userInfo") || {};
    let observable = null;
    if (!Util.isNull(config.query_bean)) {
      observable = this.pagingService.query(config, pagingConfig);
    } else if (!Util.isNull(config.interfaceId)) {
      config.query_data["PersonID"] = userInfo["PCRM_CZY02"];
      config.query_data["CompanyID"] = userInfo["PCRM_GSXX01"];
      Object.assign(config.query_data, userInfo);
      observable = this.http.get("/Inbound/invoke.do", {
        interfaceId: config.interfaceId,
        data: JSON.stringify(config.query_data),
        SessionID: userInfo["SessionID"]
      })
    }
    return Observable.create((observer) => {
      observable.subscribe(message => {
        observer.next(message);
        observer.complete();
      }, error => {
        observer.error(error);
      });
    });
  }

  post(config: { interfaceId, data }, pagingConfig?: PagingConfig): Observable<any> {
    let userInfo = this.storageService.read("userInfo");

    let observable = this.http.post("/Inbound/invoke.do", {
      interfaceId: config.interfaceId,
      data: JSON.stringify(config.data),
      SessionID: userInfo["SessionID"]
    }, pagingConfig);
    return Observable.create((observer) => {
      observable.subscribe(message => {
          observer.next(message);
          observer.complete();
        },
        error => {
          this.dialogService.showToast(error);
          observer.error(error);
        });
    });
  }

  find(query_data: MongoSearchConfig, pageConfig?: PagingConfig): Observable<any> {
    return Observable.create((observer) => {
      this.pagingService.query({
        query_bean: "mongoQuery",
        query_data: query_data
      }, pageConfig).subscribe(message => {
        observer.next(message);
      }, error => {
        this.dialogService.showToast(error);
      });
    });
  }

  apiInvoke(interfaceId: string, data: any, workflow?: any, extension?: WorkflowConfig): Observable<any> {
    let userInfo = this.storageService.read("userInfo");
    this.dialogService.showLoading("请等待");

    data.APP_XMCS = env.APP_XMCS;

    let XmlData = {};
    Object.assign(XmlData, extension);
    XmlData["interfaceId"] = interfaceId;
    XmlData["PI_USERNAME"] = userInfo["PCRM_CZY02"];
    XmlData["SessionID"] = userInfo["SessionID"];
    XmlData["data"] = JSON.stringify(Object.assign(data, userInfo));

    if (!Util.isNull(workflow)) {
      XmlData["initField"] = JSON.stringify(workflow.initField);
      XmlData["json"] = JSON.stringify({"bdbh": data.bdbh});
      if (!Util.isNull(workflow.XW01)) {
        XmlData["xwbh"] = workflow.XW01;
      }
    }

    return Observable.create((observer) => {
      this.http.post("/Inbound/api/invoke.do", XmlData).subscribe(message => {
          this.dialogService.hideLoading();
          observer.next(message);
        },
        error => {
          debugger;
          this.dialogService.hideLoading();
          observer.error(error);
        });
    });
  }

  gzlInvoke(interfaceId: string, data: any, workflow: any, extension?: WorkflowConfig) {
    return Observable.create((observer) => {
      this.get({
        interfaceId: "app.gzl.xw.search",
        query_data: {
          GZL01: workflow.GZL01,
          BZ01: workflow.BZ01
        }
      }).subscribe(XWLB => {
        debugger;
        if (XWLB.length > 0) {
          let XW = XWLB[0];
          let JK03 = JSON.parse(XW.JK03);
          data.bdbh = XW.TBLNAME;
          this.apiInvoke(interfaceId, data, {
            initField: JK03.field
          }, extension).subscribe(message => {
              this.dialogService.hideLoading();
              observer.next(message);
            },
            error => {
              debugger;
              this.dialogService.hideLoading();
              observer.error(error);
            });
        }
      });
    });
  }

  //工作流撤回
  gzlChInvoke(interfaceId: string, data: any, workflow: any) {

  }

  //工作流驳回
  gzlBhInvoke(interfaceId, data, GZL01, initField) {
    return Observable.create((observer) => {
      this.commonSearch({
        "title": "请选择回退步骤",
        "field": "BZ02",
        "query_bean": "pi.scm.app.pub.query.SearchGZLBZ",
        "query_data": {
          "GZL01": GZL01
        }
      }).onDidDismiss(message => {
        if (!Util.isNull(message)) {
          this.apiInvoke(interfaceId, data, {
            initField: initField
          }, {
            xwbh: -1,
            htbzbh: message.BZ01
          }).subscribe(message => {
            this.dialogService.hideLoading();
            observer.next(message);
          }, error => {
            debugger;
            this.dialogService.hideLoading();
            observer.error(error);
          });
        }
      });
    })
  }

  //草稿
  gzlCgInvoke(interfaceId: string, data: any, workflow: any) {

  }

  getGZLXW(GZL01, BZ01) {
    return Observable.create((observer) => {
      this.get({
        "interfaceId": "app.gzl.xw.search",
        "query_data": {
          "GZL01": GZL01,
          "BZ01": BZ01
        }
      }).subscribe(message => {
        observer.next(message);
      }, error => {
        this.dialogService.hideLoading();
        observer.error(error);
      });
    });
  }

  getGZLCZJL(PID) {
    return Observable.create((observer) => {
      this.get({
        "query_bean": "pi.scm.app.pub.query.SearchGZL_CZJL",
        "query_data": {
          "PID": PID
        }
      }).subscribe(message => {
        observer.next(message);
      }, error => {
        this.dialogService.hideLoading();
        observer.error(error);
      });
    });
  }

  commonSearch(config: any) {
    let modal = this.modalCtrl.create("CommonSearchPage", config);
    modal.present();
    return modal;
  }

  checkDataIsNull(data: any, config: any) {
    for (let key in config) {
      if (Util.isNull(data[key])) {
        this.dialogService.showAlert(config[key]);
        return false;
      }
    }
    return true;
  }
}

export class MongoSearchConfig {
  collection: string;
  query: any;
  sort?: any;
  keys?: any;
}

export class WorkflowConfig {
  sk01?: any;
  pid?: any;
  xwbh?: any;
  htbzbh?: any;
  lzry?: any;
  OA_CCRY?: any;
  OA_CCGW?: any;
  ck01?: any;
  bm01?: any;
  wldw01?: any;
  ssbm01?: any;
  qxczy01?: any;
  qx02?: any;
}
